"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const request = require('request');
const fs = require('fs');
const path = require('path');
const moments = require('moment');
const logTable = require('@xdooi/consoletable');
//
class Common {
    // 日期范围
    dateArr(max = 7) {
        // 默认最近七天
        let arr = [];
        // let date = 
        for (let i = 0; i < max; i++) {
            arr.push(moments()
                .add(-+i, 'd')
                .format('YYYY-MM-DD'));
        }
        return arr.reverse();
    }
    // 数组转对象
    arrOfobj(arr) {
        const obj = {};
        arr.forEach((item, index) => {
            obj[index] = item;
        });
        return obj;
    }
    // stop阻塞函数
    stop(delay) {
        return new Promise((reslove, reject) => {
            setTimeout(reslove, delay);
        });
    }
}
// 获取gitee信息
class GetGitee extends Common {
    // public dataObj:{}
    constructor(options) {
        super();
        this.baseUrl = 'https://gitee.com/';
        this.infos = options.infos;
        this.scope = options.max;
        this.dates = [];
        this.init();
    }
    init() {
        this.dates = this.scope ? this.dateArr(this.scope) : this.dateArr();
    }
    start() {
        return __awaiter(this, void 0, void 0, function* () {
            // 所有的数据
            const allData = [];
            for (let i = 0; i < this.infos.length; i++) {
                const info = this.infos[i];
                try {
                    const data = yield this.getInfo(info);
                    allData.push(data);
                }
                catch (err) {
                    if (err instanceof Error) {
                        console.log(err.message);
                        return false;
                    }
                    allData.push(err);
                }
            }
            // 数据排序
            allData.sort((a, b) => Number(a.count) - Number(b.count));
            allData.forEach((item, index) => item['xuhao'] = index.toString());
            this.tableLog(allData);
        });
    }
    getInfo(info) {
        // 爬取配置信息
        const options = {
            uri: this.baseUrl + info.UserName,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.53',
            },
            strictSSL: false,
        };
        // 正则表达式，匹配该用户gitee代码提交次数
        const reg = eval(`/(?<=data-content=').*(?=个贡献：(${this.dates.join('|')}))/g`);
        return new Promise((resolve, reject) => {
            request(options, (err, res, body) => {
                if (err)
                    return reject(err);
                const data = (body + '').match(reg);
                // 没有数据时
                if (!data) {
                    console.log(`${info.NickName} 的gitee用户名：${info.UserName}，爬取失败：用户不存在`);
                    resolve(Object.assign(Object.assign({}, this.arrOfobj(this.dates.map(item => 'none'))), { name: info.NickName, count: '0' }));
                    return false;
                }
                // 数据获取成功
                console.log(`${info.NickName} 的gitee用户：${info.UserName}，爬取成功 `);
                resolve(Object.assign(Object.assign({}, data), { name: info.NickName, count: data.reduce((pre, cur) => pre + Number(cur), 0).toString() }));
            });
        });
    }
    tableLog(data) {
        logTable.drawTable([
            Object.assign(Object.assign({}, this.arrOfobj(this.dates)), { name: '姓名', count: 'count', xuhao: '序号' }),
            ...data,
        ], { head: false });
    }
}
const file = '../src/ceishi.json';
const infos = JSON.parse(fs.readFileSync(path.join(__dirname, file), 'utf-8'));
const gitee = new GetGitee({ infos, max: 7 });
gitee.start();
